#!/bin/csh

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#   RUN TRAJECTORY CODE ONLY using cyclones file (output by tstorms code)
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


#===============================================================
# --- CHECK ARGUMENTS
#===============================================================

set nargin = $#argv
set xdir = ""

if ($nargin < 3) then
    echo
    echo "USAGE: " $0 " <inputfile> <outputdir>"
    echo
    echo "ARGUMENTS:"
    echo "\t<inputfile>: full path to input cyclones file listing all grid points potentially belonging to tropical storms"
    echo
    echo "\t<outputdir>: full path to output directory for multiple files; will be created if it does not exist"
    echo
    echo "\t<executabledir>: full path to directory with trajectory executables"
    echo "\t\t\t(optional: necessary only if not already in PATH)"
    echo
    exit -1
else
    set fin = $1
    set dir_out = $2
    if ($nargin > 2) then
	set xdir = $3
    endif
endif

echo "inputfile = " $fin
echo "outputdir = " $dir_out

if ( ! -e $dir_out  ) mkdir -p $dir_out

#===============================================================
# --- SET SOME PATHNAMES
#===============================================================

# --- executables
if ($xdir == "") then
    set tstorms = tstorms
    set trajectory = trajectory
else
    echo "executabledir = " $xdir
    set tstorms    = ${xdir}/tstorms
    set trajectory = ${xdir}/trajectory
endif

# --- output data
set ftraj = ${dir_out}/traj_out		# trajectories
set fori  = ${dir_out}/ori_out		# initial positions
set fstat = ${dir_out}/traj_stat_out

#===============================================================
# --- SET SOME PATHNAMES
#===============================================================

if ($xdir == "") then
    set trajectory = trajectory
else
    echo "executabledir = " $xdir
    set trajectory = ${xdir}/trajectory.exe
endif

# --- output data
set ftraj = ${dir_out}/traj_out        # trajectories
set fori  = ${dir_out}/ori_out         # initial positions
set fstat = ${dir_out}/traj_stat_out   # total counts
#===============================================================
# --- TRAJECTORY ANALYSIS
#===============================================================

# copy cyclones file to current directory so Fortran code will find it
cp $fin cyclones

# create nml_trajectory file with default values if it doesn't already exist

if ( ! -e $dir_out/nml_trajectory  ) then
  cat << eof > ${dir_out}/nml_trajectory
   &nml_trajectory
        wcrit =  17.0,
        rcrit =  400.0,
       nwcrit =  8,
      do_filt = .false.,
   &end
  eof
endif

$trajectory < ${dir_out}/nml_trajectory

head -16  stats

# move to output directory
mv   ori  $fori
mv  traj  $ftraj
mv stats  $fstat

# delete copy of cyclones file
rm -f cyclones


